package com.hadoop.avg;

import java.io.IOException;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;

public class AvgMapper extends
		Mapper<LongWritable, Text, Text, IntWritable> {
	
	//Map 출력값
	private final static IntWritable outputvalue = new IntWritable(1);
	//Map 출력키 
	private Text outputkey = new Text();
	
	//작업 구분
	private String workType;
	
	//Mapper가 생성될 때 단 한번만 실행됨.
	@Override
	public void setup(Context context) throws IOException, InterruptedException{
		workType = context.getConfiguration().get("workType");
	}
	
	//Date,Val1,Val2,Val3  Enter 기준으로 구분 
	public void map(LongWritable key, Text value, Context context){
		if(key.get() > 0){
			
			String[] columns = value.toString().split(",");
			if(columns != null && columns.length > 0){
				try{

					int firstData = Integer.parseInt(columns[1]);
					int secondData = Integer.parseInt(columns[2]);
					int thirdData = Integer.parseInt(columns[3]);
					
					
					int rstData;
					if(workType.equals("sum")){
						outputkey.set(columns[0]);
						rstData = (firstData + secondData + thirdData);
						outputvalue.set(rstData);
						context.write(outputkey, outputvalue);	
					}else if(workType.equals("both")){
						
						
						outputkey.set("Add" + columns[0]);
						rstData = (firstData + secondData + thirdData);
						outputvalue.set(rstData);
						context.write(outputkey, outputvalue);
						
						outputkey.set("Avg" + columns[0]);
						rstData = (firstData + secondData + thirdData) / 3;
						outputvalue.set(rstData);
						context.write(outputkey, outputvalue);
						
					}else{
						outputkey.set(columns[0]);
						rstData = (firstData + secondData + thirdData)/3;
						outputvalue.set(rstData);
						context.write(outputkey, outputvalue);
						//Log Count 생성 
						context.getCounter(AvgCounters.avg_total_count).increment(1);
					}
				}catch(Exception e){
				}
			}
		}
	}
}
